#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on May 9, 2014, by Junn
#
from core.views import CustomAPIView
from families.models import Family, NoneFamily, FamilyMember
from core.decorators import login_required_pro, login_required_mtd
from utils import logs, http, eggs
from users.models import User
import settings
from core.serializers import serialize_response
from rest_framework.decorators import api_view
from utils.http import Response
from core import codes
from families.serializers import FamilyMemberSerializer
from posts.models import CommentMsg


class FamiliesAction(CustomAPIView):
    '''操作多个家庭'''
    
    @login_required_pro
    def post(self, req):
        '''创建一个家庭'''
        if req.user.get_family:
            return http.failed('您已有家庭, 无法再创建. 目前仅支持一个家庭')
        
        name = req.POST.get('name', '').strip()
        about = req.POST.get('about', '').strip()
        f = Family.objects.create_family(name, req.user, about=about)
        return serialize_response(f)
    
    def delete(self, req):
        pass

class FamilyView(CustomAPIView):
    
    def get(self, req, fid):
        family = Family.objects.get_cached(fid)
        if not family or isinstance(family, NoneFamily) or  family.is_deleted():
            return http.object_not_found()

        if not family.get_member(req.user.id): #仅内部成员可查看家庭信息
            return http.resp('permission_denied')

        return serialize_response(family)
    
    @login_required_pro
    def put(self, req, fid):
        '''修改家庭信息'''
        
        family = Family.objects.get_cached(fid)
        if not family:
            return http.object_not_found()
        if not family.creator == req.user:
            return http.resp('permission_denied')
        family.update(req.DATA)
        return http.ok()
        
    @login_required_pro    
    def delete(self, req, fid):  #TODO:  
        '''创建者解散家庭, 或者将家庭转让(后续提供)
        
        '''
        family = Family.objects.get_cached(fid)
        if not family:
            return http.object_not_found()
        if not family.creator == req.user:
            return http.resp('permission_denied')      
        
        if family.has_other_members():  #解散家庭
            return http.failed('家庭内有其他成员, 不能解散家庭. 您可以选择先转让家庭')
        
        family.make_delete()
        if req.user.get_family:
            raise Exception('cached_family clear error')
        
        return http.ok()

class FamilyUsersAction(CustomAPIView):
    
    @login_required_pro
    def post(self, req, fid):
        '''添加家庭成员.
        
        成员若已注册, 则直接添加, 若未注册则先注册账号再添加. 添加成功后, 将密码返回客户端
        '''
        phone = req.POST.get('phone')
        nickname = req.POST.get('name', '')
        if not eggs.is_phone_valid(phone):
            return http.failed('手机号格式不正确') 
        
        family = Family.objects.get_cached(fid)
        if not family:
            return http.object_not_found()
        
        if family.is_members_full():
            return http.failed('成员数已达最大值')
        
        phone = eggs.normalize_phone(phone)
        user = User.objects.get_by_phone(phone)
        if not user: #用户尚未注册
            # verify_phone()                 TODO: 最好服务端要自动验证下手机号合法性
            password = eggs.random_num()
            user = User.objects._create_user(phone, password, phone=phone, 
                                             nickname=nickname, acct_type='I', is_active=False)
            member = family.add_member(user)
            
            # 'xcode': des.encryt(password, settings.SECRET_KEY)  #客户端需解密
            # API请求结果返回客户端后, 需手机用户发送密码到被添加手机号(这样可同时进行手机号合法性验证)
            #return http.ok({'sms_content': settings.SMS_CONTENT_UNSIGNEDUP.format(phone, password)})
            
            result = codes.append('ok', {'data': FamilyMemberSerializer(member).data,
                     'sms_content': settings.SMS_CONTENT_UNSIGNEDUP.format(phone, password)})
            return Response(result)  # 为添加额外的sms_content信息, 使用Response对象
        
        # 已是家庭成员
        if family.get_member(user.id):
            return http.failed('已是家庭成员, 无需重复添加')
        
        # 若用户已加入其他家庭, 返回提示信息"已加入xxx家庭, 加入新家庭需要先退出原有家庭"
        if user.get_family:
            return http.failed('用户已加入其他家庭')
        
        member = family.add_member(user)
        result = codes.append('ok', {'data': FamilyMemberSerializer(member).data, 
                                     'sms_content': settings.SMS_CONTENT})
        return Response(result)
    
    def get(self, req, fid):
        '''返回家庭成员列表'''
        
        family = Family.objects.get_cached(fid)
        if not family:
            return http.object_not_found()
        
        if not family.get_member(req.user.id): #仅内部成员可查看家庭信息
            return http.resp('permission_denied')
        
        return serialize_response(family.all_members().values())

class FamilyUserView(CustomAPIView):
    
    def get(self, req, fid, uid):
        '''查看家庭某成员信息'''
        
        f = Family.objects.get_cached(fid)
        if not f:
            return http.object_not_found()
        
        if not f.get_member(req.user.id): #仅内部成员可查看家庭信息
            return http.resp('permission_denied')
        
        member = f.get_member(int(uid))
        if not member:  #成员不在当前家庭
            user = User.objects.get_cached(uid)
            if not user: 
                return http.object_not_found()
            
            family = user.get_family
            if family: 
                return serialize_response(family.build_member(user))
            
            return serialize_response(FamilyMember(user, None))
        
        return serialize_response(member)
    
    @login_required_pro
    def put(self, req, fid, uid):
        '''修改家庭某成员信息. 仅家庭创建者和成员自己可以操作'''
        
        family = Family.objects.get_cached(fid)
        if not family:
            return http.object_not_found()
        
        member = family.get_member(int(uid))
        if not member:
            return http.failed('不是家庭成员')
        
        # 当前操作用户为家庭创建者, 或者家庭成员本人修改自己信息
        if req.user == family.creator or req.user == member.get_user:
            member.update(req.DATA, files=req.FILES)
            return serialize_response(member)
        
        logs.warn('No permission to update member %s info' % uid)
        return http.resp('permission_denied')
        
    
    @login_required_pro
    def delete(self, req, fid, uid):
        '''删除家庭成员(仅管理员有权限), 或成员退出家庭.
        仅清除家庭与成员关系, 不删除成员注册信息.
        '''
        
        family = Family.objects.get_cached(fid)
        member = family.get_member(uid)
        if not member:
            return http.failed('不是家庭成员')
        
        quit = req.REQUEST.get('q')  
        if quit == 'Y': #Y-成员退出家庭
            if req.user.is_family_creator(): 
                return http.failed('您是创建者, 不能退出家庭')
            if family.remove_member(req.user) != 1:
                return http.failed('退出家庭失败')
            
            return http.ok()
            
        # 管理员移除成员    
        if member.is_creator(): 
            return http.failed('您是家庭创建者, 不能移除自己')
        
        if not family.creator == req.user:    
            return http.resp('permission_denied')
            
        if family.remove_member(member.get_user) != 1:
            return http.failed('成员移除异常')
        
        return http.ok()
    
@api_view(['GET'])
@login_required_mtd    
def get_membership(req, fid):
    '''查询用户与家庭关系
    @param uid: 用户id
    @param phone: 电话号码. uid与phone不可全为空, 两参数同时存在时uid优先选择
     
    @return:  ship  -1-尚未注册, 0-在其他家庭, 1-在当前家庭, 2-没有家庭
    '''
    
    uid = req.REQUEST.get('uid')
    phone = req.REQUEST.get('phone')
    if not uid and not phone: 
        return http.failed('No any params passed, need uid or phone ')
    
    family = Family.objects.get_cached(fid)
    if not family:
        return http.object_not_found()     

    if uid:
        user = User.objects.get_cached(int(uid))
        return http.ok({'ship': check_membership(family, user)})
    else:
        phone = phone.strip()
        if not eggs.is_phone_valid(phone):
            logs.info('phone===>%s'% phone)
            return http.failed('手机号格式不正确')
        user = User.objects.get_by_phone(eggs.normalize_phone(phone))
        return http.ok({'ship': check_membership(family, user)})
        

#maybe this can be put in family object  TODO
def check_membership(family, user):
    if not user:
        return -1  #未注册
    if family.get_member(user.id):
        return 1  #在当前家庭
    if user.get_family:
        return 0  #在其他家庭
    return 2      #没有家庭            
        
# 拉取当前登录家庭用户看到的新增加动态数目
@api_view(['GET'])
@login_required_mtd
def pull_new_messages(req, fid):
    user = req.user
    #logs.debug('pull new messges count... (user:%s, family:%s)' % (user.id, fid))
    
    family = Family.objects.get_cached(fid)
    if not family.get_member(user.id):
        return http.resp('permission_denied')
    
    return http.ok({
        'pc': family.get_posts_unread_count(user),          #家庭新动态数
        'rc': 0,  #Regard.objects.count_new_received(user), #新收到问候数.  Repealed:已废除该数据, 为新旧版本兼容保留该属性 
        'rel_msg_c': CommentMsg.objects.count_relcomment_msgs(user) #新的与我相关的消息数
    })






